<?php

namespace Core\Widget;

use Core\Service\Image\ImageFactory;
use Model\Factory\TableGatewayFactory;

class WidgetImage extends  WidgetAbstract{

    public function form()
    {
        $html = '<div id="widgetContainer"><table cellspacing="5px" cellpadding="5px">
        <td>Tên block(*): </td>
        <td><input id="txtBlockName" name="txtBlockName" class="k-textbox" style="width: 250px" required placeholder="Nhập tên, bắt buộc" validationMessage="Chưa nhập tên">
            <span class="k-invalid-msg" data-for="txtBlockName"></span>
        </td>
        </tr>
        <tr>
        <td colspan="2">
            <div class="left" style="width: 250px; padding: 5px; border: 1px solid #ccc">
            <div style="padding-top: 5px;  text-decoration: underline; font: bold 1em Verdana, Arial, Helvetica, sans-serif;">
                Ảnh
            </div>
            <div style="padding: 5px 0px 5px 0px">
                <a href="javascript:upImgBlock()" id="lnkUpImageBlock"  style="width:100px;"><span>Upload ảnh</span></a>
                &nbsp;&nbsp;&nbsp;
                <a href="javascript:removeImgBlock()" id="lnkRemoveImageBlock"  style="width:100px;"><span>Xóa ảnh</span></a>

            </div>
            <div style="padding: 5px">
                <div style="padding: 5px ;height:150px; width:150px; border: 1px solid #CCC" align="center">
                    <img id="imgPresentBlock" src="" style="max-width:140px; max-height: 140px">
                </div>
                <div style="padding: 5px">
                    <span style="font: bold 12px Verdana, Arial, Helvetica, sans-serif;" id="spnImgPresentBlock">

                    </span>

                </div>

            </div>
            </div>
            <div class="left" style="width: 250px; padding: 5px; ">
            <table cellspacing="5px" cellpadding="5px">
                <tr>
                    <td>Rộng: </td>
                    <td><input type="number" min="10" max="960" step="10" id="txtWidthImage"  style="width: 150px" placeholder="Độ rộng ảnh"></td>
                </tr>
                <tr>
                    <td>Dài: </td>
                    <td><input type="number" min="10" max="960" step="10" id="txtHeightImage"  style="width: 150px" placeholder="Độ dài ảnh"></td>
                </tr>
                <tr>
                    <td>Link: </td>
                    <td><input class="k-textbox" style="width: 330px" id="txtLinkImage"   placeholder="Link khi click ảnh"></td>
                </tr>
            </table>
            </div>
            <div class="clear"></div>
        </td>
        </tr>
        <tr>
        <td>Css Class: </td>
        <td><input id="txtClass" class="k-textbox" style="width: 350px" placeholder="foo_class bar_class"></td>
        </tr>
        <tr>
        <td>Css Style: </td>
        <td><input id="txtStyle" class="k-textbox" style="width: 350px" placeholder="width:300px; color:red"></td>
        </tr>
        <tr>
        <td>Top text: </td>
        <td><input id="txtTopText"  class="k-textbox" style="width: 350px"  placeholder="Nhập text hiển thị phía trên ảnh" >
        </td>
        </tr>
        <tr>
        <td>Style Top text: </td>
        <td><input id="txtStyleTopText" class="k-textbox" style="width: 350px"  placeholder="width:300px; color:red" >
        </td>
        </tr>
        <tr>
        <td>Bottom text: </td>
        <td><input id="txtBottomText"  class="k-textbox" style="width: 350px"  placeholder="Nhập text hiển thị phía dưới ảnh" >
        </td>
        </tr>
        <tr>
        <td>Style Bottom text: </td>
        <td><input id="txtStyleBottomText" class="k-textbox" style="width: 350px"  placeholder="width:300px; color:red" >
        </td>
        </tr>


        </table>
        </div>';
        $javascript = '<script type="text/javascript">
            widgetValidator = $("#widgetContainer").kendoValidator().data("kendoValidator");
            $("#txtWidthImage").kendoNumericTextBox({
                format: "n0"
            });
            $("#txtHeightImage").kendoNumericTextBox({
                format: "n0"
            });
            function validateWidgetForm(){
                imagePath = $("#spnImgPresentBlock").html();
                if(!imagePath || imagePath == ""){
                    $(".block_editor_add_status").html("Chưa chọn ảnh");
                    return false;
                }
                return widgetValidator.validate();
            }
            function doAddWidget(){
                if(!validateWidgetForm()){
                    return;
                }
                blockName = $("#txtBlockName").val();
                imagePath = $("#spnImgPresentBlock").html();

                widthtextbox = $("#txtWidthImage").data("kendoNumericTextBox");
                width = widthtextbox.value();

                heighttextbox = $("#txtHeightImage").data("kendoNumericTextBox");
                height = heighttextbox.value();

                txtLinkImage = $("#txtLinkImage").val();

                txtClass = $("#txtClass").val();
                txtStyle = $("#txtStyle").val();

                txtTopText = $("#txtTopText").val();
                txtStyleTopText = $("#txtStyleTopText").val();
                txtBottomText = $("#txtBottomText").val();
                txtStyleBottomText = $("#txtStyleBottomText").val();

                widgetName = "'.$this->getProgramCode().'";


                return {name:blockName, imagePath:imagePath, width:width,
                 height:height, link:txtLinkImage, topText:txtTopText,
                 styleTopText:txtStyleTopText,bottomText:txtBottomText,
                 styleBottomText:txtStyleBottomText,
                 class:txtClass, style:txtStyle, widgetName:"'.$this->getProgramCode().'"};

            }
            function upImgBlock(){
                try{
                    var finder = new CKFinder();
                    finder.basePath = "/static/js/ckfinder/";
                    finder.selectActionFunction = setThumbFileBlock;
                    finder.popup();
                }catch(err){

                }
            }
            function setThumbFileBlock( fileUrl )
            {
                $("#imgPresentBlock").attr("src", $.getCmsThumb(fileUrl) );
                $("#spnImgPresentBlock").html(fileUrl);
                $("#lnkRemoveImageBlock").show();
            }

            function removeImgBlock(){
                $("#imgPresentBlock").attr("src", "/static/images/core/photo_required.jpg" );
                $("#spnImgPresentBlock").html("");
                $("#lnkRemoveImageBlock").hide();
                $("#lnkUpImageBlock").show();
            }

        </script>';
        return $html.$javascript;
    }

    public function render($blockInstanceItem)
    {
        $style = $blockInstanceItem->wrap_style;
        $class = $blockInstanceItem->wrap_class;
        $params = $blockInstanceItem->params;
        $paramArr = $this->getArrayFromJson($params);
        $imagePath = $paramArr['image_path'];
        $width = $paramArr['width'];
        $height = $paramArr['height'];
        $link = $paramArr['link'];
        $top_text = $paramArr['top_text'];
        $style_top_text = $paramArr['style_top_text'];
        $bottom_text = $paramArr['bottom_text'];
        $style_bottom_text = $paramArr['style_bottom_text'];

        if($link)
            $imageBody = '<a href="'.$link.'"><img src="'.$imagePath.'"></a>';
        else
            $imageBody = '<img src="'.$imagePath.'">';
        if($top_text)
            $imageHeader = '<p style="'.$style_top_text.'">'.$top_text.'</p>';
        else
            $imageHeader = '';
        if($bottom_text)
            $imageFooter = '<p style="'.$style_bottom_text.'">'.$bottom_text.'</p>';
        else
            $imageFooter = '';

        $imageCanvas = $imageHeader.$imageBody.$imageFooter;

        $html = '<div class="'.$class.'" style="'.$style.'">'.$imageCanvas.'</div>';
        return $html;

    }

    public function save($allParams)
    {

        $name = $allParams['name'];
        $class = $allParams['class'];
        $style = $allParams['style'];
        $widgetName = $allParams['widgetName'];

        $imagePath = $allParams['imagePath'];
        $width = $allParams['width'];
        $height = $allParams['height'];
        $link = $allParams['link'];
        $topText = $allParams['topText'];
        $styleTopText = $allParams['styleTopText'];
        $bottomText = $allParams['bottomText'];
        $styleBottomText = $allParams['styleBottomText'];
//           using WideImage to reside the image to appropriate size, keeping the propotion constraint

        $blockInstance = TableGatewayFactory::getBlockInstanceTable();


        $image_Factory = new ImageFactory();
        $imageService = $image_Factory->getImageService(ImageFactory::$SUPPORTER_WIDE_IMAGE);
        $absImagePath = CORE_DOCUMENT_ROOT.$imagePath;
        if(!$allParams['widgetId']){
            if($width > 0 || $height > 0){

                $newFilePath = $imageService->transformImageBlock($absImagePath,$width,$height,$name);
                $newWebFilePath = substr($newFilePath, strlen(CORE_DOCUMENT_ROOT));
            }else{
                $newWebFilePath = $imagePath;
            }
        }else{
            $blockInstance_Item = $blockInstance->getBlockInstance($allParams['widgetId']);
            $oldParamArr = $this->getArrayFromJson($blockInstance_Item->params);
            //có đổi ảnh
            if($oldParamArr['image_path'] != $imagePath){
                if($width > 0 || $height > 0){

                    $newFilePath = $imageService->transformImageBlock($absImagePath,$width,$height,$name);
                    $newWebFilePath = substr($newFilePath, strlen(CORE_DOCUMENT_ROOT));
                }else{
                    $newWebFilePath = $imagePath;
                }
            }else{
                //không đổi ảnh nhưng đổi kích thước
                if($oldParamArr['width'] != $width || $oldParamArr['height'] != $height){
                    if($width > 0 || $height > 0){

                        $newFilePath = $imageService->transformImageBlock($absImagePath,$width,$height,$name,true);
                        $newWebFilePath = substr($newFilePath, strlen(CORE_DOCUMENT_ROOT));
                    }else{
                        $newWebFilePath = $imagePath;
                    }
                }else{
                    $newWebFilePath = $imagePath;
                }
            }
        }



        $params = $this->buildJSONString(array('image_path'=>$newWebFilePath,
        'width'=>$width,'height'=>$height,'link'=>$link,'top_text'=>$topText,
            'style_top_text'=>$styleTopText,'bottom_text'=>$bottomText,
            'style_bottom_text'=>$styleBottomText));
        $blockClass = TableGatewayFactory::getBlockClassTable();

        $blockClass_Item = $blockClass->findByProgramCode($widgetName);

        if($allParams['widgetId']){
            $blockInstance->update(array(
                'block_class_id'=>$blockClass_Item->id,
                'name'=>$name, 'params'=>$params, 'wrap_class'=>$class, 'wrap_style'=>$style),$allParams['widgetId']);
            return $allParams['widgetId'] ;
        }

        else{
            $id = $blockInstance->insert(array(
                'block_class_id'=>$blockClass_Item->id,
                'name'=>$name, 'params'=>$params, 'wrap_class'=>$class, 'wrap_style'=>$style));


            return $id;
        }

    }

    public function form_update($blockInstance_Item, $blockClass_Item)
    {
        $paramArr = $this->getArrayFromJson($blockInstance_Item->params);
        $html = '<h3>'.$blockClass_Item->name.'</h3>
        <input id="txtWidgetId" type="hidden" value="'.$blockInstance_Item->id.'">
        <div id="widgetContainer"><table cellspacing="5px" cellpadding="5px">
        <td>Tên block(*): </td>
        <td><input value="'.$blockInstance_Item->name.'" id="txtBlockName" name="txtBlockName" class="k-textbox" style="width: 250px" required placeholder="Nhập tên, bắt buộc" validationMessage="Chưa nhập tên">
            <span class="k-invalid-msg" data-for="txtBlockName"></span>
        </td>
        </tr>
        <tr>
        <td colspan="2">
            <div class="left" style="width: 250px; padding: 5px; border: 1px solid #ccc">
            <div style="padding-top: 5px;  text-decoration: underline; font: bold 1em Verdana, Arial, Helvetica, sans-serif;">
                Ảnh
            </div>
            <div style="padding: 5px 0px 5px 0px">
                <a href="javascript:upImgBlock()" id="lnkUpImageBlock"  style="width:100px;"><span>Upload ảnh</span></a>
                &nbsp;&nbsp;&nbsp;
                <a href="javascript:removeImgBlock()" id="lnkRemoveImageBlock"  style="width:100px;"><span>Xóa ảnh</span></a>

            </div>
            <div style="padding: 5px">
                <div style="padding: 5px ;height:150px; width:150px; border: 1px solid #CCC" align="center">
                    <img id="imgPresentBlock" src="'.$paramArr["image_path"].'" style="max-width:140px; max-height: 140px">
                </div>
                <div style="padding: 5px">
                    <span style="font: bold 12px Verdana, Arial, Helvetica, sans-serif;" id="spnImgPresentBlock">'.$paramArr["image_path"].'</span>

                </div>

            </div>
            </div>
            <div class="left" style="width: 250px; padding: 5px; ">
            <table cellspacing="5px" cellpadding="5px">
                <tr>
                    <td>Rộng: </td>
                    <td><input value="'.$paramArr["width"].'" type="number" min="10" max="960" step="10" id="txtWidthImage"  style="width: 150px" placeholder="Độ rộng ảnh"></td>
                </tr>
                <tr>
                    <td>Dài: </td>
                    <td><input value="'.$paramArr["height"].'" type="number" min="10" max="960" step="10" id="txtHeightImage"  style="width: 150px" placeholder="Độ dài ảnh"></td>
                </tr>
                <tr>
                    <td>Link: </td>
                    <td><input value="'.$paramArr["link"].'" class="k-textbox" style="width: 330px" id="txtLinkImage"   placeholder="Link khi click ảnh"></td>
                </tr>
            </table>
            </div>
            <div class="clear"></div>
        </td>
        </tr>
        <tr>
        <td>Css Class: </td>
        <td><input value="'.$blockInstance_Item->wrap_class.'" id="txtClass" class="k-textbox" style="width: 350px" placeholder="foo_class bar_class"></td>
        </tr>
        <tr>
        <td>Css Style: </td>
        <td><input value="'.$blockInstance_Item->wrap_style.'" id="txtStyle" class="k-textbox" style="width: 350px" placeholder="width:300px; color:red"></td>
        </tr>
        <tr>
        <td>Top text: </td>
        <td><input id="txtTopText" value="'.$paramArr["top_text"].'"  class="k-textbox" style="width: 350px"  placeholder="Nhập text hiển thị phía trên ảnh" >
        </td>
        </tr>
        <tr>
        <td>Style Top text: </td>
        <td><input id="txtStyleTopText" value="'.$paramArr["style_top_text"].'" class="k-textbox" style="width: 350px"  placeholder="width:300px; color:red" >
        </td>
        </tr>
        <tr>
        <td>Bottom text: </td>
        <td><input id="txtBottomText"  value="'.$paramArr["bottom_text"].'" class="k-textbox" style="width: 350px"  placeholder="Nhập text hiển thị phía dưới ảnh" >
        </td>
        </tr>
        <tr>
        <td>Style Bottom text: </td>
        <td><input id="txtStyleBottomText"  value="'.$paramArr["style_bottom_text"].'" class="k-textbox" style="width: 350px"  placeholder="width:300px; color:red" >
        </td>
        </tr>


        </table>
        </div>';
        $javascript = '<script type="text/javascript">
            widgetValidator = $("#widgetContainer").kendoValidator().data("kendoValidator");
            $("#txtWidthImage").kendoNumericTextBox({
                format: "n0"
            });
            $("#txtHeightImage").kendoNumericTextBox({
                format: "n0"
            });
            function validateWidgetForm(){
                imagePath = $("#spnImgPresentBlock").html();
                if(!imagePath || imagePath == ""){
                    $(".block_editor_add_status").html("Chưa chọn ảnh");
                    return false;
                }
                return widgetValidator.validate();
            }
            function doUpdateWidget(){
                if(!validateWidgetForm()){
                    return;
                }
                blockName = $("#txtBlockName").val();
                imagePath = $("#spnImgPresentBlock").html();

                widthtextbox = $("#txtWidthImage").data("kendoNumericTextBox");
                width = widthtextbox.value();

                heighttextbox = $("#txtHeightImage").data("kendoNumericTextBox");
                height = heighttextbox.value();

                txtLinkImage = $("#txtLinkImage").val();

                txtClass = $("#txtClass").val();
                txtStyle = $("#txtStyle").val();

                txtTopText = $("#txtTopText").val();
                txtStyleTopText = $("#txtStyleTopText").val();
                txtBottomText = $("#txtBottomText").val();
                txtStyleBottomText = $("#txtStyleBottomText").val();

                widgetName = "'.$this->getProgramCode().'";

                txtWidgetId = $("#txtWidgetId").val();

                return {name:blockName, imagePath:imagePath, width:width,
                 height:height, link:txtLinkImage, topText:txtTopText,
                 styleTopText:txtStyleTopText,bottomText:txtBottomText,
                 styleBottomText:txtStyleBottomText,widgetId:txtWidgetId,
                 class:txtClass, style:txtStyle, widgetName:"'.$this->getProgramCode().'"};

            }
            function upImgBlock(){
                try{
                    var finder = new CKFinder();
                    finder.basePath = "/static/js/ckfinder/";
                    finder.selectActionFunction = setThumbFileBlock;
                    finder.popup();
                }catch(err){

                }
            }
            function setThumbFileBlock( fileUrl )
            {
                $("#imgPresentBlock").attr("src", $.getCmsThumb(fileUrl) );
                $("#spnImgPresentBlock").html(fileUrl);
                $("#lnkRemoveImageBlock").show();
            }

            function removeImgBlock(){
                $("#imgPresentBlock").attr("src", "/static/images/core/photo_required.jpg" );
                $("#spnImgPresentBlock").html("");
                $("#lnkRemoveImageBlock").hide();
                $("#lnkUpImageBlock").show();
            }

        </script>';
        return $html.$javascript;
    }

    public function preview($allParams)
    {
        $style = $allParams['style'];
        $class = $allParams['class'];


        $imagePath = $allParams['imagePath'];
        $width = $allParams['width'];
        $height = $allParams['height'];
        $link = $allParams['link'];
        $top_text = $allParams['topText'];
        $style_top_text = $allParams['styleTopText'];
        $bottom_text = $allParams['bottomText'];
        $style_bottom_text = $allParams['styleBottomText'];

        if($link)
            $imageBody = '<a href="'.$link.'"><img src="'.$imagePath.'"></a>';
        else
            $imageBody = '<img style="width:'.$width.'px; height:'.$height.'px;" src="'.$imagePath.'">';
        if($top_text)
            $imageHeader = '<p style="'.$style_top_text.'">'.$top_text.'</p>';
        else
            $imageHeader = '';
        if($bottom_text)
            $imageFooter = '<p style="'.$style_bottom_text.'">'.$bottom_text.'</p>';
        else
            $imageFooter = '';

        $imageCanvas = $imageHeader.$imageBody.$imageFooter;

        $html = '<div class="'.$class.'" style="'.$style.'">'.$imageCanvas.'</div>';
        return $html;
    }

    public function form_content($blockInstance_Item)
    {

    }

    public function saveContent($allParams)
    {
        // TODO: Implement saveContent() method.
    }

    public function getProgramCode()
    {
        return "Image";
    }
}